<?php

namespace App\Admin\Controllers\Auth;

use App\Admin\Controllers\Controller;
use App\Admin\Services\GrantService;
use App\Admin\Traits\RouteHelper;

class RoleController extends Controller
{
    use RouteHelper;

    protected $grantService;

    public function __construct(GrantService $grantService)
    {
        parent::__construct();
        $this->grantService = $grantService;
    }

    /**
     * 角色列表
     */
    public function index()
    {
        $limit = request()->get('limit') ?? 30;
        $roles = $this->grantService->getRoles('', $limit);
        $items = $this->grantService->setPermissionsToRole($roles->items());

        if (request()->ajax()) {
            return $this->laytable($roles->total(), $items);
        }

        return view('admin.role.index', ['roles' => $roles]);
    }

    /**
     * 添加角色-前台
     */
    public function create()
    {
        //獲取所有權限提供前台選擇
        $permissions = $this->grantService->getPermissions();
        return view('admin.role.create', ['permissions' => $permissions]);
    }

    /**
     * 添加角色-後台
     */
    public function store()
    {
        $roleName    = request()->get('roleName');
        $permissions = request()->get('permissions')[0] ?? '';

        try {
            // 添加角色
            $role = $this->grantService->createRoles($roleName);
            // 添加權限
            if (isset($permissions)) {
                $permissions = explode(',', $permissions);
                $role->givePermissionTo($this->grantService->getPermissionIn($permissions));
            }
            return $this->success('操作成功');
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 修改角色
     */
    public function edit()
    {
        $role = $this->grantService->getRoles(request()->id);
        //獲取用戶的所有權限
        $allPermissions = $this->grantService->getPermissions();
        $permissions    = $role->permissions;
        $ownPermission  = [];
        foreach ($permissions as $permission) {
            $ownPermission[] = $permission->name;
        }
        return view('admin.role.edit', [
            'role'          => $role,
            'permissions'   => $allPermissions,
            'ownPermission' => $ownPermission,
        ]);
    }

    /**
     * 保存角色修改
     */
    public function update()
    {
        $roleId      = request()->get('roleId');
        $roleName    = request()->get('roleName');
        $permissions = request()->get('permissions')[0] ?? '';

        try {
            // 更新角色名
            $this->grantService->updateRoles($roleName, $roleId);
            $role = $this->grantService->getRoles($roleId);
            // 修改角色權限
            if (isset($permissions)) {
                $permissions = (array)explode(',', $permissions);
                $role->syncPermissions($this->grantService->getPermissionIn($permissions));
            }
            return $this->success('操作成功');
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 刪除角色
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws
     */
    public function delete()
    {
        $id = request('id');

        if (empty($id)) {
            return $this->failure('未選擇', [], 200);
        }

        try {
            if ($this->grantService->deleteRoles($id)) {
                return $this->success('刪除成功');
            }
        } catch (\Exception $e) {
            $this->failure($e->getMessage());
        }
    }

    /**
     * 對角色添加授權
     */
    public function assignRolePermission()
    {
        $id           = request()->get('roleId');
        $permissionId = request()->get('permissionId');
        $role         = $this->grantService->getRole($id);
        $permission   = $this->grantService->getPermission($permissionId);

        if ($role->givePermissionTo($permission->name)) {
            return $this->success('操作成功');
        }

        return $this->failure('操作失敗');
    }

    public function export()
    {

    }

    public function getRolePermission($role_id)
    {
        $role        = $this->grantService->getRoles($role_id);
        $permissions = $role->permissions;
        $permissions = array_column($permissions->toArray(), 'route');
        $permissions = implode(",", $permissions);

        return explode(",", $permissions);
    }
}
